<template>
  <!--
  model绑定
  rules规则
  ref id-->
  <el-form :model="userForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="电话号码">
      <el-input v-model="userForm.phone" disabled></el-input>
    </el-form-item>
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="userForm.userName"></el-input>
    </el-form-item>
    <el-form-item label="用户密码" prop="userPassword">
      <el-input v-model="userForm.userPassword" type="password"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="reUserPassword">
      <el-input v-model="userForm.reUserPassword" type="password"></el-input>
    </el-form-item>
    <!--
    action上传地址
    :show-file-list显示文件集合
    on-success文件上传成功回调
    :before-upload 上传文件之前的验证
    -->
    <el-form-item>
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/admin/upload?module=avatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="userForm.avatarUrl" :src="userForm.avatarUrl" class="avatar" alt="头像">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit()">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import axios from '../../utils/request'

export default {
  name: 'UserEdit',
  created () {
    this.init()
  },
  data () {
    /**
     * 当失去焦距的时候
     * 验证用户输入的用户名名字
     * @param rule
     * @param value 用户输入的用户名
     * @param callback
     */
    let validateUserName = async (rule, value, callback) => {
      let response = await axios({
        method: 'get',
        url: '/api/user/checkName/' + value
      })
      if (response.data === true) {
        callback()
      } else {
        callback(new Error('输入的名字已经被注册，请修改用户名'))
      }
    }
    let validateUserPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.userForm.userPassword !== value) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }
    }
    return {
      userForm: {},
      rules: {
        userName: [
          { required: true, message: '输入用户名', trigger: 'blur' },
          {min: 6, max: 12, message: '长度在6到12个字符', trigger: 'blur'},
          {validator: validateUserName, trigger: 'blur'}
        ],
        userPassword: [
          { required: true, message: '输入用户名', trigger: 'blur' }
        ],
        reUserPassword: [
          {validator: validateUserPassword, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    async init () {
      let response = await axios({
        method: 'get',
        url: '/api/user/now'
      })
      this.userForm = response.data
      console.log(response)
    },
    handleAvatarSuccess (res, file) {
      console.log(res)
      this.userForm.avatarUrl = res.data
      console.log(this.$store.state.user.token)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /**
     * 提交表单
     */
    onSubmit () {
      // 1 验证窗体电话好吗是否正常输入
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let response = await axios({
            method: 'put',
            url: '/api/user/updateUserById',
            data: this.userForm
          })
          if (response.code === '200') {
            this.$message.success('更新信息成功，请重新登录')
          } else {
            alert('更新失败，请重试')
          }
        } else {
          return false
        }
      }
      )
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
